package com.itmumu.miniwechat.common.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itmumu.miniwechat.common.domain.response.ApiResult;
import com.itmumu.miniwechat.common.exception.CommonErrorEnum;
import com.itmumu.miniwechat.common.exception.JwtVerifyException;
import com.itmumu.miniwechat.common.utils.ContextUtil;
import com.itmumu.miniwechat.common.utils.JwtUtils;
import com.itmumu.miniwechat.user.domain.po.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * jwt拦截器
 */
@Component
public class JwtInteceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("Access-Token");

        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(token)) {
            throw new JwtVerifyException("token不能为空");
        }

        // JWT异常处理
        try {
            JwtUtils.verifyToken(token);

            DecodedJWT tokenInfo = JwtUtils.getTokenInfo(token);
            User user = new User();
            user.setUid(tokenInfo.getClaim("uid").as(Integer.class));
            user.setNickname(tokenInfo.getClaim("username").asString());
            user.setMobile(tokenInfo.getClaim("mobile").asString());
            user.setEmail(tokenInfo.getClaim("email").asString());

            // 将用户信息存入上下文
            ContextUtil.setUserInfo(user);

            return true;
        } catch (Exception e) {
            map.put("msg", "token不合法");
            map.put("state", false);
            response.setContentType("application/json;charset=UTF-8");

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(ApiResult.success().code(CommonErrorEnum.UNAUTHORIZED.getCode()).message(CommonErrorEnum.UNAUTHORIZED.getMessage()));
            response.getWriter().println(jsonResponse);
            return false;
        }

    }


    /**
     * 执行完成
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the handler (or {@link HandlerMethod}) that started asynchronous
     * execution, for type and/or instance examination
     * @param ex any exception thrown on handler execution, if any; this does not
     * include exceptions that have been handled through an exception resolver
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextUtil.clear();
    }
}
